package com.x.service.transactional;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.x.dao.ConfigurationDAO;
import com.x.dao.ShipmentsDAO;
import com.x.dao.TransitTimeDAO;
import com.x.model.Configuration;
import com.x.model.Shipments;
import com.x.model.TransitTime;

@Component("transitTimeService")
public class TransitTimeService {

	@Autowired
	private ShipmentsDAO shipmentsDAO;
	@Autowired
	private TransitTimeDAO transitTimeDAO;
	@Autowired
	private ConfigurationDAO configurationDAO;

	public boolean upload(MultipartFile file) {
		byte[] buffer;
		try {
			buffer = file.getBytes();
			String contents = new String(buffer, "UTF-8");
			String[] contentList = contents.split("\\r\\n|\\n|\\r|\\n\\r");
			List<TransitTime> tts = new ArrayList<>();
			List<Configuration> configs = new ArrayList<>();
			Timestamp ts = new Timestamp(System.currentTimeMillis());
			for (String content : contentList) {
				String[] result = content.split(",");
				int priority = 0;
				TransitTime tt = new TransitTime();
				tt.setFc(result[0]);
				tt.setShipMethod(result[1]);
				tt.setProvince(result[2]);
				tt.setCity(result[3]);
				tt.setDistrict(result[4]);
				tt.setTt(Integer.valueOf(result[5]));
				if (result[2].equals("all")) {
					priority = 1;
				} else if (result[3].equals("all")) {
					priority = 2;
				} else if (result[4].equals("all")) {
					priority = 3;
				} else {
					priority = 4;
				}
				tt.setPriority(priority);
				tts.add(tt);

				List<Shipments> shipments = shipmentsDAO.getShipments(
						result[0], result[1], result[2], result[3], result[4]);
				if (shipments != null) {
					for (Shipments shipment : shipments) {
						Configuration config = new Configuration();
						config.setFc(shipment.getFc());
						config.setShipMethod(shipment.getShipMethod());
						config.setProvince(shipment.getProvince());
						config.setCity(shipment.getCity());
						config.setDistrict(shipment.getDistrict());
						config.setShipments(shipment.getShipments());
						config.setTt(Integer.valueOf(result[5]));
						config.setCreatetime(ts);
						configs.add(config);
					}
				}
			}
			transitTimeDAO.trancate();
			transitTimeDAO.upload(tts);
			configurationDAO.upload(configs);

		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}
}
